package org.sbi.satvik.model;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import org.sbi.satvik.beans.SatvikFromBean;
import org.sbi.satvik.beans.SearchDataBean;
import org.sbi.satvik.utility.HibernateUtil;
import org.sbi.satvik.utility.StringObjectToJson;

import com.google.gson.Gson;

public class SearchDataModel {

	public static String getSerachData(SearchDataBean searchDataBean){
		
		Gson gson = new Gson();
		List<SatvikFromBean> satvikFromBeanlist= getListOfUsers(searchDataBean);
		
		JSONObject jsonObject = new JSONObject();
		int i = 0;
		for (SatvikFromBean satvikFromBean : satvikFromBeanlist) {
			
			
			String jsonString = gson.toJson(satvikFromBean);
			
			try {
				JSONObject jsonDataObject=StringObjectToJson.stringconverter(jsonString);
				jsonObject.put("row"+i, jsonDataObject);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		i++;
		}
		if(i == 0){
			return "nodataFound";
		}
		
		System.out.println(jsonObject.toString());
		
		System.out.println(satvikFromBeanlist.size());
		
		return jsonObject.toJSONString();
	}
	
	
	public static List<SatvikFromBean> getListOfUsers(SearchDataBean searchDataBean){
		
		System.out.println(searchDataBean.getEndDate());
		 List<SatvikFromBean> satvikFromlist = new ArrayList<SatvikFromBean>();
		 Session session = HibernateUtil.openSession();
		 Transaction tx = null;	
		 try {
			 tx = session.getTransaction();
			 tx.begin();
			/* satvikFromlist = session.createQuery("from SatvikFromBean where EntryDate between "
			 		+ "'"+searchDataBean.getStartDate()+"' and '"+searchDataBean.getEndDate()+"' ").list();	*/
			 
			 Query query = session.createQuery("from SatvikFromBean where EntryDate between ? and ? and hiddenFlag=1");
			
			 query.setString(0, searchDataBean.getStartDate());
			 query.setString(1, searchDataBean.getEndDate());
			 
			 satvikFromlist = query.list();
			 
			 tx.commit();
		 } catch (Exception e) {
			 if (tx != null) {
				 tx.rollback();
			 }
			 e.printStackTrace();
		 } finally {
			 session.close();
		 }
		 return satvikFromlist;
	}
}
